<template>
  <div class="questions">
    <el-card shadow="never">
      <template #header>
        <div class="table-header">
          <span>题目列表</span>
          <div style="display: flex; gap: 10px">
            <el-button @click="downloadTemplate">📥 下载Excel模板</el-button>
            <el-button type="success" @click="triggerFileUpload">📤 批量导入</el-button>
            <el-button type="primary" @click="showAddDialog">+ 新增题目</el-button>
          </div>
        </div>
      </template>

      <!-- 隐藏的文件输入 -->
      <input
        ref="fileInput"
        type="file"
        accept=".xlsx,.xls"
        style="display: none"
        @change="handleFileUpload"
      />

      <!-- 筛选条件 -->
      <el-form :inline="true" style="margin-bottom: 20px">
        <el-form-item label="分类">
          <el-input
            v-model="filter.category"
            placeholder="输入分类名称筛选"
            clearable
            style="width: 200px"
            @keyup.enter="handleFilterChange"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="filter.type" placeholder="全部" clearable @change="handleFilterChange">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="单选题" value="single"></el-option>
            <el-option label="多选题" value="multiple"></el-option>
            <el-option label="判断题" value="truefalse"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="paginatedData" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="120"></el-table-column>
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            {{ scope.row.category || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 'single'" type="success">单选题</el-tag>
            <el-tag v-else-if="scope.row.type === 'multiple'" type="warning">多选题</el-tag>
            <el-tag v-else-if="scope.row.type === 'truefalse'" type="info">判断题</el-tag>
            <el-tag v-else type="info">{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="question" label="题目" show-overflow-tooltip></el-table-column>
        <el-table-column label="选项" width="300">
          <template #default="scope">
            <div v-if="scope.row.type === 'single' || scope.row.type === 'multiple'">
              <div v-if="scope.row.options" style="font-size: 12px; line-height: 1.5;">
                {{ formatOptions(scope.row.options) }}
              </div>
              <span v-else style="color: #999;">无选项</span>
            </div>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column label="正确答案" width="100">
          <template #default="scope">
            <el-tag type="success" size="small">{{ scope.row.answer || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: center">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          layout="prev, pager, next, total"
          :total="total"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="分类" prop="category">
          <el-input v-model="form.category" placeholder="请输入分类名称（如：安全教育、校园常识等）"></el-input>
        </el-form-item>
        <el-form-item label="题目类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="single">单选题</el-radio>
            <el-radio label="multiple">多选题</el-radio>
            <el-radio label="truefalse">判断题</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题目" prop="question">
          <el-input
            v-model="form.question"
            type="textarea"
            rows="3"
            placeholder="请输入题目"
          ></el-input>
        </el-form-item>
        <el-form-item label="选项" v-if="form.type !== 'truefalse'">
          <div v-for="(option, index) in form.options" :key="index" style="margin-bottom: 10px">
            <el-input v-model="option.value" placeholder="请输入选项内容">
              <template #prepend>{{ option.label }}</template>
              <template #append>
                <el-button
                  v-if="form.options.length > 2"
                  @click="removeOption(index)"
                  icon="Delete"
                ></el-button>
              </template>
            </el-input>
          </div>
          <el-button @click="addOption" icon="Plus" size="small">添加选项</el-button>
        </el-form-item>
        <el-form-item label="正确答案" prop="answer">
          <el-input
            v-model="form.answer"
            placeholder="单选/判断填写单个选项（如A），多选填写多个选项用逗号分隔（如A,B,C）"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { questionApi } from '@/api/question'

const questions = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('新增题目')
const formRef = ref(null)
const fileInput = ref(null)
const currentPage = ref(1)
const pageSize = 10
const loading = ref(false)

const filter = reactive({
  category: null,
  type: null
})

const form = reactive({
  id: null,
  category: '',
  type: 'single',
  question: '',
  options: null,
  answer: ''
})

const rules = {
  category: [{ required: false, message: '请输入分类名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
  question: [{ required: true, message: '请输入题目', trigger: 'blur' }],
  answer: [{ required: true, message: '请输入正确答案', trigger: 'blur' }]
}

const paginatedData = computed(() => {
  return questions.value
})

const loadData = async () => {
  loading.value = true
  try {
    // 加载题目列表
    const questionResponse = await questionApi.listQuestions(
      currentPage.value,
      pageSize,
      filter.category || null,
      filter.type || null
    )
    questions.value = questionResponse.data.records || []
    total.value = questionResponse.data.total || 0
    
    // 处理选项格式（如果options是JSON字符串，转换为对象）
    questions.value.forEach(q => {
      if (q.options && typeof q.options === 'string') {
        try {
          q.options = JSON.parse(q.options)
        } catch (e) {
          q.options = null
        }
      }
    })
  } catch (error) {
    // 错误信息已在request拦截器中处理
  } finally {
    loading.value = false
  }
}

// 格式化选项显示
const formatOptions = (options) => {
  if (!options) return '无选项'
  try {
    let optionsArray = options
    if (typeof options === 'string') {
      optionsArray = JSON.parse(options)
    }
    if (Array.isArray(optionsArray)) {
      return optionsArray.map((opt, index) => {
        const letter = String.fromCharCode(65 + index) // A, B, C, D...
        return `${letter}. ${opt}`
      }).join(' | ')
    }
    return '格式错误'
  } catch (e) {
    return '格式错误'
  }
}

const showAddDialog = () => {
  dialogTitle.value = '新增题目'
  form.id = null
  form.category = ''
  form.type = 'single'
  form.question = ''
  form.options = null
  form.answer = ''
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑题目'
  form.id = row.id
  form.category = row.category
  form.type = row.type
  form.question = row.question
  // 处理options格式
  if (row.options) {
    if (typeof row.options === 'string') {
      try {
        form.options = JSON.parse(row.options)
      } catch (e) {
        form.options = null
      }
    } else {
      form.options = JSON.parse(JSON.stringify(row.options))
    }
  } else {
    form.options = null
  }
  form.answer = row.answer
  dialogVisible.value = true
}

const addOption = () => {
  if (!form.options) {
    form.options = []
  }
  const labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
  if (form.options.length < labels.length) {
    form.options.push({
      label: labels[form.options.length],
      value: ''
    })
  }
}

const removeOption = (index) => {
  if (form.options) {
    form.options.splice(index, 1)
    // 重新分配标签
    form.options.forEach((opt, i) => {
      opt.label = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'][i]
    })
  }
}

const handleSave = async () => {
  if (!formRef.value) return
  
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const saveData = {
          category: form.category,
          type: form.type,
          question: form.question,
          answer: form.answer,
          options: form.type !== 'truefalse' && form.options ? JSON.stringify(form.options) : null
        }

        if (form.id) {
          await questionApi.updateQuestion(form.id, saveData)
        } else {
          await questionApi.createQuestion(saveData)
        }

        ElMessage.success('保存成功')
        dialogVisible.value = false
        loadData()
      } catch (error) {
        // 错误信息已在request拦截器中处理
      }
    }
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这个题目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await questionApi.deleteQuestion(row.id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      // 错误信息已在request拦截器中处理
    }
  })
}

const handlePageChange = (page) => {
  currentPage.value = page
  loadData()
}

const handleFilterChange = () => {
  currentPage.value = 1
  loadData()
}

// Excel导出函数
const downloadTemplate = async () => {
  try {
    const response = await questionApi.downloadTemplate()
    const csvContent = response.data
    
    // 创建Blob并下载
    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', '题库导入模板.csv')
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('模板已下载')
  } catch (error) {
    // 错误信息已在request拦截器中处理
  }
}

// 触发文件上传
const triggerFileUpload = () => {
  fileInput.value?.click()
}

// 处理文件上传
const handleFileUpload = async (e) => {
  const file = e.target.files?.[0]
  if (!file) return
  
  try {
    ElMessage.loading({
      message: '正在导入...',
      duration: 0
    })
    
    const response = await questionApi.importQuestions(file)
    
    ElMessage.closeAll()
    if (response.data) {
      ElMessage.success(`成功导入 ${response.data.successCount} 条题目`)
      
      // 显示错误信息（如果有）
      if (response.data.errorMessages && response.data.errorMessages.length > 0) {
        ElMessage.warning(response.data.errorMessages.join('\n'))
      }
      
      // 重新加载数据
      loadData()
    }
  } catch (error) {
    ElMessage.closeAll()
    // 错误信息已在request拦截器中处理
  }
  
  // 重置文件输入
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 本地导入方式（后备方案）
const handleFileUploadLocal = async (file) => {
  try {
    const text = await file.text()
    const lines = text.split('\n').filter(line => line.trim())
    
    // 跳过BOM标记和分隔符行
    let dataLines = lines
    if (dataLines[0]?.includes('sep=')) {
      dataLines = dataLines.slice(1)
    }
    
    // 获取表头
    const headers = dataLines[0].split(',').map(h => h.trim().replace(/^"|"$/g, ''))
    const headerIndexMap = {
      category: headers.findIndex(h => h.includes('分类')),
      type: headers.findIndex(h => h.includes('题目类型')),
      question: headers.findIndex(h => h.includes('题目内容')),
      optionA: headers.findIndex(h => h.includes('选项A')),
      optionB: headers.findIndex(h => h.includes('选项B')),
      optionC: headers.findIndex(h => h.includes('选项C')),
      optionD: headers.findIndex(h => h.includes('选项D')),
      answer: headers.findIndex(h => h.includes('正确答案'))
    }
    
    // 解析数据行
    const importedQuestions = []
    
    for (let i = 1; i < dataLines.length; i++) {
      const line = dataLines[i].trim()
      if (!line) continue
      
      // 简单的CSV解析（处理引号）
      const cells = line.split(',').map(cell => cell.trim().replace(/^"|"$/g, ''))
      
      const category = cells[headerIndexMap.category]?.trim() || ''
      const type = cells[headerIndexMap.type]?.trim() || 'single'
      const questionText = cells[headerIndexMap.question]?.trim() || ''
      const answer = cells[headerIndexMap.answer]?.trim() || ''
      
      if (!questionText || !answer) {
        ElMessage.warning(`第 ${i + 1} 行数据不完整，已跳过`)
        continue
      }
      
      // 构建选项
      let options = null
      if (type !== 'truefalse' && type !== 'judge') {
        options = []
        const optionLabels = ['A', 'B', 'C', 'D']
        const optionIndices = [
          headerIndexMap.optionA,
          headerIndexMap.optionB,
          headerIndexMap.optionC,
          headerIndexMap.optionD
        ]
        
        for (let j = 0; j < optionLabels.length; j++) {
          const optionText = cells[optionIndices[j]]?.trim()
          if (optionText) {
            options.push({
              label: optionLabels[j],
              value: optionText
            })
          }
        }
      }
      
      // 准备导入数据
      const questionData = {
        category: category,
        type: type,
        question: questionText,
        answer: answer,
        options: options ? JSON.stringify(options) : null
      }
      
      try {
        await questionApi.createQuestion(questionData)
        importedQuestions.push(questionData)
      } catch (error) {
        ElMessage.warning(`第 ${i + 1} 行导入失败: ${error.message || '未知错误'}`)
      }
    }
    
    if (importedQuestions.length === 0) {
      ElMessage.warning('未找到有效的题目数据')
      return
    }
    
    ElMessage.success(`成功导入 ${importedQuestions.length} 条题目`)
    loadData()
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败，请检查文件格式是否正确')
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.questions {
  width: 100%;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-card) {
  width: 100%;
}
</style>

